<template>
    <div class="select_buy_order_detail_container">
        <headerTemplate slot="header" ref="header"
                        :toolbar_buttons="headerOption.toolbar_buttons"
                        :searchForm="searchForm"
                        @event="handleHeaderEvent">
            <template slot="left_search">
                <div class="label">已选分录数量：<span class="tip">{{ selectionList.length }}</span></div>
            </template>
        </headerTemplate>
        <div class="table_area">
            <vxeTableTemplate ref="selectTable" :data="dataList" :options.sync="tableOptions"
                              @event="handleTableEvent" />
        </div>
    </div>
</template>

<script>
import { mapState } from "vuex";
import provide from "@common/mixins/provide";
import clothing from "@jxc/utils/clothing";

export default {
    extends: provide,
    name: "SelectBuyOrderDetail",
    props: {
        data: {
            type: Object,
            default: null,
        },
    },
    data() {
        const _this = this;
        return {
            searchForm: {
                state: '',
            },
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            _this.getList();
                        },
                    },
                ],
            },
            dataList: [],
            selectionList: [],
            tableOptions: {
                ref: "SelectBuyOrderDetailTable",
                container: ".select_buy_order_detail_container",
                multiSelect: true,
                rowConfig: {
                    keyField: 'sid',
                },
                checkboxConfig: {
                    reserve: true,
                },
                columns: [],
                baseColumns: [
                    {
                        label: "采购单号",
                        prop: "order_code",
                        align: "center",
                    },
                    {
                        label: "物料",
                        prop: "goods_name",
                        align: "center",
                    },
                    {
                        label: "规格",
                        prop: "spec_info",
                        align: "center",
                    },
                    {
                        label: "数量",
                        prop: "qty",
                        align: "center",
                    },
                    {
                        label: "单位",
                        prop: "unit_name",
                        align: "center",
                    },
                    {
                        label: "单价",
                        prop: "price",
                        align: "center",
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 4),
                    },
                    {
                        label: "金额",
                        prop: "amount",
                        align: "center",
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "退货数量",
                        prop: "return_qty",
                        align: "center",
                    },
                    {
                        label: "退货金额",
                        prop: "return_amount",
                        align: "center",
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                ],
                pagination: {
                    pageIndex: 1,
                },
                getMaxHeight() {
                    return $(_this.getActiveTabsContainer()).height() * 0.8 - 100;
                },
            },
        };
    },
    computed: {
        ...mapState('jxc', ['setting']),
    },
    watch: {
        data: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        async init() {
            const _this = this;
            if (!_this.data) {
                return;
            }
            await _this.storeDispatch('jxc/initSetting');
            _this.searchForm = {
                state: '',
            };
            _this.initTableOptions();
            _this.clearSelection();
            _this.getList(true);
        },
        initTableOptions() {
            const _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            let pagination = $.extend({}, _this.tableOptions.pagination);
            columns = clothing.resetTableColumns(_this.setting, columns);
            columns.forEach(item => {
                delete item.editRender;
            });
            if (clothing.isClothing(_this.setting)) {
                pagination = false;
            }
            _this.tableOptions = $.extend({}, _this.tableOptions, {
                columns,
                pagination,
            });
        },
        clearSelection() {
            const _this = this;
            _this.selectionList = [];
            this.$nextTick(() => {
                _this.SelectBuyOrderDetailTable.clearCheckboxRow();
                _this.SelectBuyOrderDetailTable.clearCheckboxReserve();
            });
        },
        getList(init) {
            const _this = this;
            _this.dataList = [];
            if (init) {
                _this.tableOptions = _this.resetTablePagination(_this.tableOptions);
            }
            let queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            queryData.supplier_sid = _this.data.supplier_sid;
            queryData.selected_list = _this.data.selected_list || [];
            if (clothing.isClothing(_this.setting)) {
                queryData.nopage = '1';
            }
            return _this.fetchData(_this.$api.API_QueryJxcBuyOrderDetailList4Return, queryData).then(res => {
                _this.dataList = clothing.transferDetailList(_this.setting, res.data);
                _this.tableOptions = _this.setTableTotal(_this.tableOptions, res);
                _this.$nextTick(() => {
                    _this.initSelection();
                });
            });
        },
        initSelection() {
            const _this = this;
            if (!_this.SelectBuyOrderDetailTable || !_this.$utils.isNotEmptyList(_this.selectionList)) {
                return;
            }
            let selection = _this.selectionList.map(item => item.sid);
            _this.dataList.forEach(item => {
                if (selection.indexOf(item.sid) !== -1) {
                    _this.SelectBuyOrderDetailTable.setCheckboxRow(item, true);
                }
            });
        },
        handleHeaderEvent(event) {
            const _this = this;
            _this.searchForm = $.extend({}, _this.searchForm, event.searchForm);
            if (event.type === "search") {
                _this.getList(true);
            } else if (event.type === "refresh") {
                _this.getList(true);
            }
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                let selectionList = this.SelectBuyOrderDetailTable.getCheckboxRecords();
                let reserveList = this.SelectBuyOrderDetailTable.getCheckboxReserveRecords();
                if (this.$utils.isNotEmptyList(reserveList)) {
                    selectionList = selectionList.concat(reserveList);
                }
                this.selectionList = selectionList;
            }
        },
        confirm(event) {
            const _this = this;
            if (!_this.$utils.isNotEmptyList(_this.selectionList)) {
                _this.$message.error('请选择采购订单！');
                return;
            }
            let list = _this.selectionList.map(item => {
                if (clothing.isClothing(_this.setting)) {
                    return $.extend({}, item);
                }
                let qty = item.qty, qty4base = item.qty4base;
                if (_this.$utils.isNotEmpty(item.return_qty)) {
                    qty = _this.$utils.accSubtr(qty, item.return_qty);
                }
                if (_this.$utils.isNotEmpty(item.return_qty4base)) {
                    qty4base = _this.$utils.accSubtr(qty4base, item.return_qty4base);
                }
                return {
                    buy_order_sid: item.order_sid,
                    buy_detail_sid: item.sid,
                    goods_sid: item.goods_sid,
                    order_code: item.order_code,
                    goods_name: item.goods_name,
                    spec_info: item.spec_info,
                    qty, qty4base,
                    remain_qty4base: qty4base,
                    unit_name: item.unit_name,
                    unit_qty: item.unit_qty,
                    price: item.price,
                    amount: _this.$utils.accMul(qty, item.price),
                    price_list: (item.price_list || []).map(t => $.extend({}, t)),
                };
            });
            event._component.initDataList(list);
            _this.$emit('event', 'closeDialog');
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.select_buy_order_detail_container {
    width: 100%;
    height: 100%;
    overflow: hidden;

    /deep/.label {
        font-size: 14px;
        padding: 0 10px;

        .tip {
            font-size: 16px;
            font-weight: bold;
            padding: 0 5px;
            color: #409EFF;
        }
    }
}
</style>
